<template>
  <lay-table :page="page" :columns="columns" :height="tableHeight" :data-source="dataSource" :loading="loading"
    :resize="true" :default-toolbar="defaultToolbars" v-model:selected-keys="selectedKeys" style="height: 100%;">
    <template v-slot:toolbar>
      <lay-button size="xs" type="primary" @click="changeAddVisible">新增</lay-button>
      <lay-button size="xs" @click="remove">删除</lay-button>
    </template>
    <template #status="{ row }">
      <lay-switch :model-value="row.status" @change="changeStatus($event, row)" onswitch-text="启用"
        unswitch-text="禁用"></lay-switch>
    </template>
    <template v-slot:operator="{ row }">
      <lay-button size="xs" @click="update(row)" type="primary">编辑</lay-button>
      <!-- <lay-button size="xs">查看</lay-button> -->
    </template>
  </lay-table>

  <!-- 新增 -->
  <lay-layer v-model="addVisible" :shade="false" :area="['500px', '']" :resize="true" :title="'新增用户'" :btn="addAction">
    <div style="padding: 20px;">
      <lay-form :model="newUser" ref="addUserForm">
        <lay-form-item label="账号" prop="username" required>
          <lay-input v-model="newUser.username"></lay-input>
        </lay-form-item>
        <lay-form-item label="密码" prop="password" required>
          <lay-input v-model="newUser.password" type="password"></lay-input>
        </lay-form-item>
        <lay-form-item label="手机号" prop="phone" required>
          <lay-input v-model="newUser.phone"></lay-input>
        </lay-form-item>
        <lay-form-item label="邮箱" prop="email">
          <lay-input v-model="newUser.email"></lay-input>
        </lay-form-item>
        <lay-form-item label="昵称" prop="nickname">
          <lay-input v-model="newUser.nickname"></lay-input>
        </lay-form-item>

        <lay-form-item label="角色" prop="role" required>
          <lay-radio v-for="role in roleList" v-model="newUser.role" name="role" :value="role.id"
            :label="role.name"></lay-radio>
        </lay-form-item>
      </lay-form>
    </div>
  </lay-layer>

  <!-- 修改信息 ========================================== -->
  <lay-layer v-model="updateVisible" :shade="false" :area="['500px', '']" :resize="true" :title="'修改角色'"
    :btn="updateAction">
    <div style="padding: 20px;">
      <lay-form :model="updateUser" ref="updateForm">
        <lay-form-item label="ID" prop="id">
          <lay-input v-model="updateUser.id" :disabled="true"></lay-input>
        </lay-form-item>
        <lay-form-item label="账号" prop="username" required>
          <lay-input v-model="updateUser.username"></lay-input>
        </lay-form-item>
        <lay-form-item label="手机号" prop="phone">
          <lay-input v-model="updateUser.phone"></lay-input>
        </lay-form-item>
        <lay-form-item label="邮箱" prop="email">
          <lay-input v-model="updateUser.email"></lay-input>
        </lay-form-item>
        <lay-form-item label="昵称" prop="nickname">
          <lay-input v-model="updateUser.nickname"></lay-input>
        </lay-form-item>

        <lay-form-item label="角色" prop="role" required>
          <lay-radio v-for="role in roleList" v-model="updateUser.role" name="role" :value="role.id"
            :label="role.name"></lay-radio>
        </lay-form-item>
      </lay-form>
    </div>
  </lay-layer>
</template>

<script setup>
import { ref, reactive, onMounted, h, computed } from 'vue';
import { layer } from '@layui/layui-vue';
import api from '@/api';

const queryForm = ref({
  pageNum: 1,
  pageSize: 20,
  province: ["广西"],
  city: [],
  county: [],
  town: [],
  village: [],
})

const loading = ref(true);
const selectedKeys = ref([]);
// 计算表格高度
// const tableHeight = computed(() => {
//   return window.innerHeight - 85 + 'px'
// })

const page = reactive({ current: 1, limit: 20, limits: [20, 50, 100, 500], total: 10, layout: ["page", "limits", "prev", "refresh", "count", "next", "skip",] });
// 分页、排序、筛选等参数
const change = (page) => {
  queryForm.value.pageNum = page.current;
  queryForm.value.pageSize = page.limit;
  loading.value = true;
  initDataList();
}
page.change = change; // attach change handler to page prop per layui-vue new API

// 获取数据列表
const roleList = ref([]);
const dataSource = ref([]);
const initDataList = async () => {
  loading.value = true
  await api.post("system/user/search", queryForm.value).then((res) => {
    if (res.code === 200) {
      console.log(res.data);
      loading.value = false
      dataSource.value = res.data || []
      page.total = res.total;
    } else {
      layer.msg(res.msg, { icon: 2, time: 5000 });
    }
  })
}

// 新增
const addVisible = ref(false);
const changeAddVisible = async () => {
  roleList.value = (await api.get('/system/role/list')).data.filter(item => item.status);
  console.log(roleList.value);
  addVisible.value = !addVisible.value;
}
const newUser = reactive({
  username: "admin",
  role: "user",
})
const addUserForm = ref();

const addUserHandler = async () => {
  let response = await api.get('/system/user/add', {
    username: newUser.username,
    password: newUser.password,
    phone: newUser.phone,
    email: newUser.email,
    nickname: newUser.nickname,
    role: newUser.role,
  });

  if (response.code === 200) {
    layer.msg(response.msg, { icon: 1, time: 1000 });
    initDataList(); // 刷新用户列表
    addVisible.value = !addVisible.value;
  } else {
    layer.msg(response.msg, { icon: 2, time: 2000 });
  }
}

const addAction = ref([
  {
    text: "添加",
    callback: () => {
      if (addUserForm.value.validate()) {
        addUserHandler();
      } else {
        layer.msg("请填写完整信息！", { icon: 2, time: 2000 });
        return;
      }
    }
  },
  {
    text: "取消",
    callback: () => {
      layer.msg("操作已取消！", { icon: 3, time: 1000 });
      addVisible.value = !addVisible.value;
    }
  }
])

// 修改
const updateVisible = ref(false);
const updateUser = reactive({
  id: null,
  username: "",
  phone: "",
  email: '',
  nickname: '',
  status: null,
  role: null,
})
const updateForm = ref();

async function update(row) {
  console.log('@row:', row.role);
  roleList.value = (await api.get('/system/role/list')).data.filter(item => item.status);
  updateUser.id = row.id;
  updateUser.username = row.username;
  updateUser.phone = row.phone;
  updateUser.email = row.email;
  updateUser.nickname = row.nickname;
  updateUser.status = row.status;
  updateUser.role = row.role;
  updateVisible.value = !updateVisible.value;
}

const updateHandler = async () => {
  let response = await api.get('/system/user/update', {
    id: updateUser.id,
    username: updateUser.username,
    phone: updateUser.phone,
    email: updateUser.email,
    nickname: updateUser.nickname,
    status: updateUser.status,
    role: updateUser.role,
  });

  if (response.code === 200) {
    layer.msg(response.msg, { icon: 1, time: 1000 });
    initDataList(); // 刷新角色列表
  } else {
    layer.msg(response.msg, { icon: 2, time: 2000 });
  }
}

const updateAction = ref([
  {
    text: "保存",
    callback: () => {
      if (updateForm.value.validate()) {
        updateHandler().then(() => {
          updateVisible.value = false;
        });

      } else {
        layer.msg("请填写完整信息！", { icon: 2, time: 2000 });
        return;
      }
    }
  },
  {
    text: "取消",
    callback: () => {
      layer.msg("操作已取消！", { icon: 3, time: 1000 });
      updateVisible.value = !updateVisible.value;
    }
  }
])


// 切换启用状态
const changeStatus = async (isChecked, row) => {
  roleList.value = (await api.get('/system/role/list')).data.filter(item => item.status);
  dataSource.value.forEach((item) => {
    if (item.id === row.id) {
      updateUser.id = item.id;
      updateUser.username = item.username;
      updateUser.phone = item.phone;
      updateUser.email = item.email;
      updateUser.nickname = item.nickname;
      updateUser.status = isChecked;
      updateUser.role = item.role
      updateHandler();
    }
  })
}

// 删除
async function remove() {
  if (selectedKeys.value.length === 0) {
    layer.msg("请选择要删除的用户！", { icon: 2 });
    return;
  } else {
    for (let id of selectedKeys.value) {
      // 这里可以调用API删除用户
      const response = await api.get('/system/user/delete', { id: id });
      if (response.code === 200) {
        selectedKeys.value = [];
        initDataList(); // 刷新用户列表
        console.log(`删除用户 ${id} 成功！`, response);
        layer.msg(response.msg, { icon: 1, time: 1000 })
      } else {
        layer.msg(response.msg, { icon: 2, time: 1000 })
      }
    }
  }
}


const columns = [
  { fixed: "left", type: "checkbox", title: "复选" },
  { title: "ID", key: "id", width: "70px", align: 'center', sort: true },
  { title: "用户名", key: "username", align: 'center', ellipsisTooltip: true, },
  { title: "密码", key: "password", align: 'center', ellipsisTooltip: true, hide: true },
  { title: "手机号", key: "phone", align: 'center', ellipsisTooltip: true, },
  { title: "邮箱", key: "email", align: 'center', ellipsisTooltip: true, },
  { title: "昵称", key: "nickname", align: 'center', ellipsisTooltip: true, },
  { title: "角色", key: "role_name", align: 'center', ellipsisTooltip: true, },
  { title: "创建时间", key: "created_time", align: 'center', ellipsisTooltip: true, },
  { title: "状态", key: "status", align: 'center', customSlot: "status" },
  { title: "操作", key: "operator", width: "90px", align: 'center', customSlot: "operator", fixed: "right", ignoreExport: true }
]
const defaultToolbars = [
  "filter",
  {
    icon: "layui-icon-refresh",
    title: "刷新",
    onClick: () => {
      initDataList();
      console.log("刷新")
    }
  },
  "export",
  "print",
]


onMounted(() => {
  initDataList();
});
</script>

<style scoped>
.layui-card-body {
  padding: 5px !important;
}
</style>